module app.repository.ArticleRepository;

import hunt.entity.repository;
import hunt.framework.Simplify;
import app.model.Article;
import std.format;

class ArticleRepository : EntityRepository!(Article, ulong)
{

    this()
    {
        super(defaultEntityManager());
    }

    /**
    * 分页查询
    * @Parameters    page    int
    * @Parameters    perPage    int
    * @return    Page!Article
    */
    Page!Article findArticlesByPagination(int page = 1, int perPage = 7)
    {
        page = page < 1 ? 1 : page;
        perPage = perPage < 1 ? 7 : perPage;
        return _manager.createQuery!(Article)("SELECT * FROM article",
                new Pageable(page - 1, perPage)).getPageResult();
    }

    /**
    * 分页查询2，带关键词查找
    * @Parameters    page    int
    * @Parameters    perPage    int
    * @Parameters    keywords    string
    * @return    Page!Article
    */
    Page!Article findArticlesByPagination(int page = 1, int perPage = 7, string keywords = "")
    {
        import std.format : format;

        page = page < 1 ? 1 : page;
        perPage = perPage < 1 ? 7 : perPage;

        if (keywords == "")
        {
            return this.findArticlesByPagination(page, perPage);
        }
        // sql传参会报错，此处采用字符串格式化
        string sql = format("SELECT * FROM article WHERE title LIKE '%%%s%%'", keywords);
        return _manager.createQuery!(Article)(sql, new Pageable(page - 1, perPage)).getPageResult();
    }

    /**
    * 搜索文章
    * @Parameters    words    string
    * @Parameters    return    Article[]
    */
    Article[] searchArticle(string words)
    {
        import std.format : format;

        // import std.stdio;

        string sql = format("SELECT * FROM article WHERE article.title LIKE '%%%s%%'", words);
        // writeln(sql);
        return _manager.createQuery!(Article)(sql).getResultList();
    }
}
